package com.example.wuqiu.utils;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.atomic.AtomicReference;

@Slf4j
public class ReentrantSpinLock {

    private static AtomicReference<Object> sign = new AtomicReference<>();

    public static <T> void lock(T t, boolean reentrantFlag) {
        // 若可重入标志为true, 且若尝试加锁的对象和已加的锁中的对象相同，可重入,并加锁成功
        if (reentrantFlag && t == sign.get()) {
            return;
        }
        //If the lock is not acquired, it can be spun through CAS
        while (!sign.compareAndSet(null, t)) {
            // DO nothing
            log.info("自旋一会.");
        }
    }

    public static <T> void unlock(T t) {
        // 锁的线程和目前的线程相等时，才允许释放锁
        if (t == sign.get()) {
            sign.compareAndSet(t, null);
        }
    }
}
